package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.UserDTO;
import com.yuelao.yuelao_backend.dto.request.LoginRequest;
import com.yuelao.yuelao_backend.dto.request.RegisterRequest;
import com.yuelao.yuelao_backend.dto.request.SubmitGuideRequest;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.entity.UserSettings;
import com.yuelao.yuelao_backend.mapper.UserSettingsMapper;
import com.yuelao.yuelao_backend.service.AuthService;
import com.yuelao.yuelao_backend.service.UserService;
import com.yuelao.yuelao_backend.service.CoinService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;
    
    @Resource
    private CoinService coinService;
    
    @Resource
    private UserSettingsMapper userSettingsMapper;

    @Override
    @Transactional
    public UserDTO register(RegisterRequest request) {
        // 1. 校验参数
        if (!StringUtils.hasText(request.getPhone()) || !StringUtils.hasText(request.getPassword())) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "手机号或密码不能为空");
        }

        // 2. 检查手机号是否已注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, request.getPhone());
        long count = userService.count(queryWrapper);
        if (count > 0) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "该手机号已被注册");
        }

        // 3. 创建用户
        User user = new User();
        user.setPhone(request.getPhone());
        user.setNickname("新用户_" + System.currentTimeMillis()); // 默认昵称
        user.setStatus(1); // 1-正常
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 4. 加密密码并存储
        user.setPassword(passwordEncoder.encode(request.getPassword()));

        boolean saved = userService.save(user);
        if (!saved) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "注册失败，请稍后重试");
        }

        // 5. 初始化用户相关数据
        initializeUserData(user.getId());

        return userService.convertToUserDTO(user);
    }


    @Override
    public boolean submitGuide(Long userId, SubmitGuideRequest request) {
        // 引导信息实际上是更新用户资料的一部分，复用 UserService 的 updateUserInfo 方法
        // 需要将 SubmitGuideRequest 转换为 UpdateUserRequest
        // 这里简化处理，直接将部分字段映射过去
        // 实际项目中，SubmitGuideRequest 应该包含 UpdateUserRequest 的所有字段或部分字段
        // 或者单独处理引导信息逻辑
        return userService.updateUserInfo(userId, request.toUpdateUserRequest());
    }
    
    /**
     * 初始化用户数据
     * 包括：货币账户、用户设置
     * @param userId 用户ID
     */
    private void initializeUserData(Long userId) {
        // 1. 初始化用户货币账户（通过查询触发自动初始化）
        coinService.getCoinBalance(userId);
        
        // 2. 初始化用户设置（使用数据库默认值）
        UserSettings settings = new UserSettings();
        settings.setUserId(userId);
        // 通知设置 - 默认全部开启
        settings.setNotificationLike(true);
        settings.setNotificationMatch(true);
        settings.setNotificationMessage(true);
        settings.setNotificationComment(true);
        settings.setNotificationSystem(true);
        // 隐私设置 - 默认全部开启
        settings.setPrivacyShowAge(true);
        settings.setPrivacyShowLocation(true);
        settings.setPrivacyShowOnline(true);
        settings.setPrivacyAllowVisitor(true);
        settings.setPrivacyAllowStrangerMessage(true);
        settings.setCreatedAt(LocalDateTime.now());
        settings.setUpdatedAt(LocalDateTime.now());
        userSettingsMapper.insert(settings);
        
        // 注意：user_profiles 表采用延迟初始化，在用户首次更新资料时创建
    }
}